package com.example.communist_app_api.controller.web;

import com.example.communist_app_api.db.dto.WordDTO;
import com.example.communist_app_api.db.pojoDto.User;
import com.example.communist_app_api.db.pojoDto.Word;
import com.example.communist_app_api.exception.GlobalException;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.service.WordService;
import com.example.communist_app_api.util.JwtUtils;
import com.example.communist_app_api.util.R;
import com.example.communist_app_api.util.ReadExcel.excelRead;
import com.example.communist_app_api.vo.web.req.WordCreateReq;
import com.example.communist_app_api.vo.web.req.WordCommonReq;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * @author Brother Sheng Editor
 * @version 1.0
 * Create by 2023/2/24 17:07
 */
@RestController
@RequestMapping("/sensitiveWord")
@Api("敏感词controller控制器")
public class SensitiveWordController {
    @Autowired
    private WordService wordService;
    @Autowired
    private UserService userService;

//    public static final String NORMAL = "正常";
//
//    public static final String LOCAL = "失效";

    public static final String ZERO = "0";

    public static final String ONE = "1";

    @PostMapping("/create")
    @ApiOperation("新增敏感词")
    public R createSensitiveWord(@RequestBody WordCreateReq req ,@RequestHeader("token") String token){
        //操作员operatorId是登录该web的人
        Integer webUserId = getUserIdByTokenAndWeb(token);
        Word word = new Word();
        word.setWord(req.getWord());
        word.setType(req.getType());
        word.setStatus(req.getStatus());
        word.setRemark(req.getRemark());
        word.setOperatorId(String.valueOf(webUserId));
        Integer insert = wordService.insert(word);
        if(insert ==0){
            throw new GlobalException("新增敏感词过程出错");
        }
        return R.ok("新增敏感词成功");
    }

    @PostMapping("/delete")
    @ApiOperation("删除敏感词")
    public R deleteSensitiveWord(@RequestParam("id") @NotBlank Integer id){
        Integer delete = wordService.delete(id);
        if(delete ==0){
            throw new GlobalException("删除敏感词过程出错");
        }
        return R.ok("删除敏感词成功");
    }

    @PostMapping("/update")
    @ApiOperation("更新敏感词")
    public R updateSensitiveWord(@RequestBody WordCommonReq req, @RequestHeader("token") String token){
        //操作员operatorId是登录该web的人
        Integer webUserId = getUserIdByTokenAndWeb(token);
        Word word = new Word();
        word.setWord(req.getWord());
        word.setType(req.getType());
        word.setStatus(req.getStatus());
        word.setRemark(req.getRemark());
        word.setOperatorId(String.valueOf(webUserId));
        word.setId(req.getId());
        Integer update = wordService.update(word);
        if(update ==0){
            throw new GlobalException("删除敏感词过程出错");
        }
        return R.ok("更新敏感词成功");
    }

    @PostMapping("/select")
    @ApiOperation("查询敏感词")
    public R selectSensitiveWord(@RequestBody WordCommonReq req){
        Word word = new Word();
        word.setWord(req.getWord());
        word.setType(req.getType());
        word.setStatus(req.getStatus());
        word.setRemark(req.getRemark());
        word.setId(req.getId());
        PageInfo<Word> pageInfo= wordService.selectByCondition(word,req.getPageNum(),req.getPageSize());
        return R.ok("查询敏感词成功").put("pageInfo",pageInfo);
    }

    @PostMapping("/batchInsertExcelToList")
    @ApiOperation("批量插入excel转List")
    public R testExcelToList(MultipartFile multipartFile, @RequestHeader("token") String token) throws IntrospectionException, IOException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException {

        //从EXEL表第二行开始
        final int startRow = 2;
        //EXEL表最后一行
        final int EndRow = -1;
        //页数为Sheet1
        final String SheetNum = "0";
        List<List<Object>> wordDTOList = excelRead.readExcelByPOJO(multipartFile,startRow, EndRow, WordDTO.class,SheetNum);
        Optional.ofNullable(wordDTOList)
                .orElseThrow(()-> new GlobalException("处理失败"));
        //说明这转换只适合于只有Sheet1的情况，否则会报错
        List<Object> wordDTOS = wordDTOList.get(Integer.parseInt(SheetNum));
        List<WordDTO>   wordInsertList = new LinkedList<>();
        Collections.addAll(wordInsertList,wordDTOS.toArray(new WordDTO[0]));
        //操作员operatorId是登录该web的人
        Integer webUserId = getUserIdByTokenAndWeb(token);
        for (WordDTO wordDTO:wordInsertList) {
            if (wordDTO.getStatus().equals("正常")) {
                wordDTO.setStatus("0");
            }else {
                wordDTO.setStatus("1");
            }

            wordDTO.setOperatorId(webUserId+"");
        }
        Integer insertNumber = wordService.batchInsert(wordInsertList);
        if (insertNumber == 0) {
            throw new GlobalException("批量新增失败");
        }
        return R.ok().put("wordInsertList",wordInsertList);
    }

    private  Integer getUserIdByTokenAndWeb(@RequestHeader("token") String token) {
        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();
        User userInfo = userService.getUserInfo(username);
        return userInfo.getId();
    }
}
